/*
 * GoodsDetailInfoFragment.java
 * business
 *
 * Created by SunDing on 2016/9/28.
 *
 * Copyright (c) 2016年 yidiandao. All rights reserved.
 */

package com.yidiandao.business.ui.goodsdetail.info;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.net.http.SslError;
import android.os.Build;
import android.support.v4.widget.NestedScrollView;
import android.text.TextUtils;
import android.view.View;
import android.webkit.SslErrorHandler;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;

import com.yidiandao.business.R;
import com.yidiandao.business.base.BaseFragment;
import com.yidiandao.business.ui.widget.view.ExtendNestedScrollView;
import com.yidiandao.business.utils.AnimatorUtils;
import com.yidiandao.business.utils.SysUtils;
import com.yidiandao.business.utils.UIUtils;

/**
 * 商品详情
 */
public class GoodsDetailInfoFragment extends BaseFragment implements GoodsDetailInfoContract.View {
    private GoodsDetailInfoContract.Presenter mPresenter;
    private WebView mWebView;
    private ImageView mIvToTop;
    private ExtendNestedScrollView mExtendNestedScrollView;
    private boolean isVisibility;

    private boolean isOpening, isHiding;

    private int mContentWidth;
    private String mUrl;

    public static GoodsDetailInfoFragment getInstance() {
        return new GoodsDetailInfoFragment();
    }

    @Override
    public void setPresenter(GoodsDetailInfoContract.Presenter presenter) {
        mPresenter = presenter;
    }

    @Override
    public String getPagerTag() {
        return GoodsDetailInfoFragment.class.getSimpleName();
    }

    @Override
    public void showToast(String text) {
    }

    @Override
    protected void initViews() {
        mWebView = (WebView) mRootView.findViewById(R.id.web_view);
        mIvToTop = (ImageView) mRootView.findViewById(R.id.iv_to_top);
        mExtendNestedScrollView =
                (ExtendNestedScrollView) mRootView.findViewById(R.id.extendNestedScrollView);

        //获取关于网页的设置
        WebSettings mSettings = mWebView.getSettings();
    /*    // 加上这个属性后。。。html的图片就会以单列显示就不会变形占了别的位置
        mSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
        mWebView.setInitialScale(135);
        // 设置缩放工具的显示
        mSettings.setBuiltInZoomControls(true);
        // 设置支持缩放
        mSettings.setSupportZoom(false);
        //不显示webView缩放按钮
        mSettings.setDisplayZoomControls(false);
        //使javascript的设置有效,交互时必须设置
        mSettings.setJavaScriptEnabled(true);
        mSettings.setUseWideViewPort(false);
        mSettings.setSavePassword(false);
        mSettings.setLoadWithOverviewMode(true);
        mSettings.setDomStorageEnabled(true);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { //使用https和http混合方式
            mSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }*/

        // 加上这个属性后。。。html的图片就会以单列显示就不会变形占了别的位置
        mSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        // 让缩放显示的最小值为起始
        mWebView.setInitialScale(5);
        // 设置缩放工具的显示
        mSettings.setBuiltInZoomControls(true);
        // 设置支持缩放
        //不显示webView缩放按钮
        mSettings.setDisplayZoomControls(false);
        //使javascript的设置有效,交互时必须设置
        mSettings.setJavaScriptEnabled(true);
        mSettings.setUseWideViewPort(true);
        mSettings.setLoadWithOverviewMode(true);
        mSettings.setDomStorageEnabled(true);
        mSettings.setDatabaseEnabled(true);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { //使用https和http混合方式
            mSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }
        //注册方法获取view的宽度
        //        mWebView.addJavascriptInterface(new JavaScriptInterface(), "HTMLOUT");

        mWebView.setWebViewClient(new GoodsDetailWebViewClient());

        //对于Android 3.0以上版本，Android系统开放了部分JS接口。
        // 因此在这个版本范围下，尽管客户端自身没有使用addJavascriptInterface方法
        // 黑客仍可以透过系统开放的JS接口实施恶意操作, 故移除一下接口
        mWebView.removeJavascriptInterface("searchBoxJavaBridge_");
        mWebView.removeJavascriptInterface("accessibility");
        mWebView.removeJavascriptInterface("accessibilityTraversal");

        initEvent();
    }

    /*  class JavaScriptInterface {
            @JavascriptInterface
            public void getContentWidth(String value) {
                if (value != null) {
                    mContentWidth = Integer.parseInt(value);
                    int scale = SysUtils.getScreenWidth(mActivity) * 100 / mContentWidth;
                    mWebView.setInitialScale(scale);
                }
            }
        }
    */
    @Override
    protected int getLayoutId() {
        return R.layout.fragment_goods_detail_info;
    }

    public void setGoodsInfo(String url) {
        if (!TextUtils.isEmpty(url)) {
            mUrl = url;
            mWebView.loadUrl(url);
        }
    }

    @Override
    public void onDestroy() {
        mWebView.removeAllViews();
        mWebView.destroy();
        super.onDestroy();
    }

    private void initEvent() {
        mIvToTop.setOnClickListener(
                new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        mExtendNestedScrollView.smoothScrollTo(0, 0);
                    }
                });

        mExtendNestedScrollView.setOnScrollChangeListener(
                new NestedScrollView.OnScrollChangeListener() {
                    @Override
                    public void onScrollChange(
                            NestedScrollView v,
                            int scrollX,
                            int scrollY,
                            int oldScrollX,
                            int oldScrollY) {
                        if ((scrollY - oldScrollY) > 0) {
                            hideAnimator(mIvToTop);
                        } else {
                            if (scrollY > SysUtils.getScreenHeight(UIUtils.getContext())) {
                                // 超过屏幕高度，开始显示
                                // 动画显示
                                showAnimator(mIvToTop);
                            } else {
                                // 隐藏
                                // 动画隐藏
                                hideAnimator(mIvToTop);
                            }
                        }
                    }
                });
    }

    /**
     * 显示动画
     */
    private void showAnimator(View view) {
        AnimatorUtils.showToTopAnimator(
                view,
                isVisibility,
                isOpening,
                new AnimatorListenerAdapter() {
                    @Override
                    public void onAnimationStart(Animator animation) {
                        isOpening = true;
                    }

                    @Override
                    public void onAnimationEnd(Animator animation) {
                        isVisibility = true;
                        isOpening = false;
                    }
                });
    }

    /**
     * 隐藏动画
     */
    private void hideAnimator(final View view) {
        AnimatorUtils.hideToTopAnimator(
                view,
                isVisibility,
                isHiding,
                new AnimatorListenerAdapter() {
                    @Override
                    public void onAnimationStart(Animator animation) {
                        isHiding = true;
                    }

                    @Override
                    public void onAnimationEnd(Animator animation) {
                        view.setVisibility(View.GONE);
                        isVisibility = false;
                        isHiding = false;
                    }
                });
    }

    private class GoodsDetailWebViewClient extends WebViewClient {

        @Override
        public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
            //handler.cancel(); // Android默认的处理方式
            handler.proceed(); // 接受所有网站的证书
            //handleMessage(Message msg); // 进行其他处理
        }

        /*  @Override
        public void onPageFinished(WebView view, String url) {
            mWebView.loadUrl("javascript:window.HTMLOUT.getContentWidth(document
            .getElementsByTagName('html')[0].scrollWidth);");
        }*/
    }
}
